import router from '@/router';
import { useUserStore } from '@/store';

import { AxiosSetting, InternalAxiosRequestConfig, IResponse } from './types';

let sessionOver = false;

/**
 * 自定义的Axios相关配置
 */
const setting: AxiosSetting = {
  /**
   * 接口地址
   */
  baseURL: import.meta.env.VITE_API_BASE_URL,

  /**
   * 接口成功返回状态码
   */
  code: 200,

  /**
   * 接口请求超时时间
   */
  timeout: 60000,

  /**
   * 默认接口请求类型
   * 可选值：application/json 或 multipart/form-data
   */
  defaultHeader: 'application/json',
};

/**
 * 默认请求拦截器，处理请求参数
 *
 * @param requestConfig Axios的请求配置
 * @returns Axios的请求配置
 */
const defaultRequestInterceptors = (
  requestConfig: InternalAxiosRequestConfig
) => {
  if (requestConfig.method === 'get' && requestConfig.params) {
    let url = requestConfig.url as string;
    url += '?';
    const keys = Object.keys(requestConfig.params);
    keys.forEach((key) => {
      if (
        requestConfig.params[key] !== undefined &&
        requestConfig.params[key] !== null
      ) {
        url += `${key}=${encodeURIComponent(requestConfig.params[key])}&`;
      }
    });
    url = url.substring(0, url.length - 1);
    requestConfig.params = {};
    requestConfig.url = url;
  }
  return requestConfig;
};

/**
 * 默认响应拦截器
 *
 * @param response 自定义的Axios响应对象
 * @returns 处理后的响应对象
 */
const defaultResponseInterceptors = (response: IResponse<any>) => {
  if (response instanceof Blob) {
    // 如果是文件流，直接过。
    return response;
  }

  if (response.code === setting.code) {
    // 成功返回数据
    return response.data;
  }

  if (response.code === 600) {
    // 登录过期
    if (!sessionOver) {
      sessionOver = true;
      MessageInfo.confirm(
        response.message,
        () => {
          sessionOver = false;
          try {
            const userStore = useUserStore();
            userStore.logoutCallBack();
          } catch (e) {
            console.log(e);
          } finally {
            router.replace('/login');
          }
        },
        {
          title: '提示',
          hideCancel: true,
          closable: false,
        }
      );
    }
  } else {
    // 其它错误情况
    MessageInfo.error((response as any).message);
    return Promise.reject(new Error(response.message));
  }
};

export { defaultRequestInterceptors, defaultResponseInterceptors };

export default setting;
